package com.xuecheng.content.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanWorkService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseBaseService courseBaseService;

    //查看课程大纲计划
    @Override
    public ResponseResult<TeachplanVo> treeNodes(Long courseId) {
        //查询课程计划所有数据
        List<TeachplanVo> voList = teachplanMapper.treeNodes(courseId);
        //筛选出一级大纲
        TeachplanVo oneVo = null;
        for (TeachplanVo vo : voList) {
            //一级大纲grade==1
            if (vo.getGrade().equals(1)){
                oneVo=vo;
                //只需要选出一个即可
                break;
            }
        }
        //筛选二级目录
        List<TeachplanVo> twoList=new ArrayList<>();
        for (TeachplanVo vo : voList) {
            //二级目录grade==2
            if (vo.getGrade().equals(2)){
                twoList.add(vo);
            }
        }
        //一级大纲绑定二级目录
        oneVo.setTeachPlanTreeNodes(twoList);
        //筛选三级节点
        for (TeachplanVo twoVo : twoList) {
            List<TeachplanVo> threeList=new ArrayList<>();
            for (TeachplanVo vo : voList) {
                //三级节点父id==二级目录id
                if (vo.getParentid().equals(twoVo.getId())){
                    threeList.add(vo);
                }
            }
            //二级目录绑定三级节点
            twoVo.setTeachPlanTreeNodes(threeList);
        }
        //返回一级大纲
        return ResponseResult.okResult(oneVo);
    }


    @Override
    public ResponseResult<TeachplanVo> treeNodes_stream(Long courseId) {
        //查询课程计划所有数据
        List<TeachplanVo> voList = teachplanMapper.treeNodes(courseId);
        //筛选一级大纲  一级大纲grade==1
        TeachplanVo oneVo = voList.stream().filter(vo -> vo.getGrade().equals(1)).findFirst().get();
        //筛选二级目录  二级目录grade==2
        List<TeachplanVo> twoList = voList.stream().filter(vo -> vo.getGrade().equals(2)).collect(Collectors.toList());
        //一级大纲绑定二级目录
        oneVo.setTeachPlanTreeNodes(twoList);
        //筛选三级节点
        for (TeachplanVo twoVo : twoList) {
            //三级节点父id==二级目录id
            List<TeachplanVo> threeList = voList.stream().filter(vo -> vo.getParentid().equals(twoVo.getId())).collect(Collectors.toList());
            //三级节点绑定二级目录
            twoVo.setTeachPlanTreeNodes(threeList);
        }
        //返回一级大纲
        return ResponseResult.okResult(oneVo);
    }

    //新增或修改课程计划
    @Override
    public ResponseResult<TeachplanVo> saveOrUpdateTeachPlan(TeachplanDto teachplanDto) {
        //查询数据库课程信息
        CourseBase courseBase = courseBaseService.getById(teachplanDto.getCourseId());
        //校验课程状态
        if (StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)){
            //已发布的不允许新增和修改
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //dto转为数据库实体
        Teachplan teachplan = BeanHelper.copyProperties(teachplanDto, Teachplan.class);
        //补全信息
        teachplan.setCreateDate(new Date());//创建时间
        //一级大纲在创建课程时已完成添加
        //设置二级目录时绑定parentId
        if(teachplan.getGrade().equals(2)){
            //获取一级大纲id
            Teachplan oneVo = this.lambdaQuery().eq(Teachplan::getCourseId, teachplanDto.getCourseId())
                    .eq(Teachplan::getGrade, 1).one();
            teachplan.setParentid(oneVo.getId());
        }
        //设置三级节点时，设置章节数目
        //三级目录parentId从前端接收，不需要绑定
        //章节数目只在新增时添加，修改时不变
        if (teachplan.getId()==null && teachplan.getGrade().equals(3)){
            //章节数目+1
            courseBase.setPlanNum(courseBase.getPlanNum()+1);
            //更新数据库
            courseBaseService.updateById(courseBase);
        }
        //写入或更新课程计划表
        this.saveOrUpdate(teachplan);
        //新增或修改后需要重新审核
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        courseBaseService.updateById(courseBase);
        //返回200
        return ResponseResult.okResult();
    }

    //删除课程计划
    @Override
    public ResponseResult deleteTeachPlan(Long teachplanId) {
        //查询数据库获取课程状态、课程计划
        Teachplan teachplan = this.getById(teachplanId);
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        //校验课程状态 已发布、审核已通过、已提交的不允许删除
        if (StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //删除目录或节点
        if (teachplan.getGrade().equals(2)){
            //删除二级目录
            //查询二级目录下三级节点的数量，大于0则不允许删除
            Long count = this.lambdaQuery().eq(Teachplan::getParentid, teachplan.getId()).count();
            if (count>0){
                throw new BusinessException(ErrorCode.DELETEERROR);
            }
            this.removeById(teachplanId);
        }else {
            //删除三级节点
            //章节数目-1
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            //更新数据库
            courseBaseService.updateById(courseBase);
            this.removeById(teachplanId);
        }
        //删除一级大纲无前端操作，在删除课程时一并删除
        return ResponseResult.okResult();
    }
}
